<template>
	<div>
		<el-form
			:rules="rules"
			ref="ruleFormRef"
			:model="state.form"
			label-width="auto"
			style="max-width: 600px"
		>
			<el-form-item label="项目名称：" prop="projectName">
				<el-input  maxlength="20" show-word-limit v-model="state.form.projectName" />
			</el-form-item>
			<el-form-item label="项目总额：" prop="amount">
				<el-input v-model.number="state.form.amount"  />
			</el-form-item>
			<el-form-item label="联系方式：" prop="contacts">
				<el-input v-model.number="state.form.wxCode"  />
			</el-form-item>
			<el-form-item label="接单方式：" prop="projectType">
				<el-select v-model="state.form.projectType" placeholder="请选择">
					<el-option label="自营" :value="0" />
					<el-option label="第三方" :value="1" />
				</el-select>
			</el-form-item>
			<el-form-item label="项目类别：" prop="projectCate">
				<el-select v-model="state.form.projectCate" placeholder="请选择">
					<el-option label="结清项目" :value="0" />
					<el-option label="周期性项目" :value="1" />
				</el-select>
			</el-form-item>
			<el-form-item label="交付时间：">
				<el-date-picker
					v-model="state.form.deliveryTime"
					type="date"
					placeholder="选择日期"
					:size="size"
					format="YYYY年MM月DD日"
					value-format="YYYY年MM月DD日"
				/>
			</el-form-item>

			<el-form-item label="是否创建付款订单:">
				<el-radio-group v-model="state.form.createOrder" @change="toggleOrderValidation">
					<el-radio :value="true">需要</el-radio>
					<el-radio :value="false">不需要</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-row v-if="state.form.createOrder">
				<el-col :span="24">
					<el-form-item label="订单名称：">
						<el-input maxlength="20" show-word-limit v-model="state.form.enterOrderValidate.orderName" />
					</el-form-item>
					<el-form-item label="订单金额：" prop="orderAmount">

						<el-input-number  :min="0.01" :max="5000" :precision="2"  :step="10"  v-model="state.form.enterOrderValidate.orderAmount" />
					</el-form-item>
					<el-form-item label="支付类型：">
						<el-select v-model="state.form.enterOrderValidate.payType" placeholder="请选择">
							<el-option label="创建支付链接" :value="0" />
							<el-option label="微信直付" :value="1" />
							<el-option label="淘宝直付" :value="2" />
							<el-option label="支付宝直付" :value="3" />
						</el-select>
					</el-form-item>

					<el-form-item v-if="state.form.enterOrderValidate.payType !== 0" label="支付凭证：" prop="paymentProof">
						<!--						<el-upload-->
						<!--							class="avatar-uploader"-->
						<!--							:action="fileUploadUrl"-->
						<!--							:show-file-list="false"-->
						<!--							:on-success="handleAvatarSuccess"-->
						<!--						>-->
						<!--							<img v-if="state.from.enterOrderValidate"  class="avatar" />-->
						<!--							<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>-->
						<!--						</el-upload>-->
					</el-form-item>
					<el-form-item v-else label="推送用户支付方式：">
						<el-radio-group v-model="state.form.enterOrderValidate.sendType">
							<el-radio :value="0">短信</el-radio>
							<el-radio :value="1">公众号</el-radio>
							<el-radio :value="2">暂不填写</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item v-if="state.form.enterOrderValidate.sendType !==2" v-model="state.form.enterOrderValidate.sendId" :label="state.form.enterOrderValidate.sendType ===0?'手机号：':'选择用户'">
						<el-input v-if="state.form.enterOrderValidate.sendType === 0 " placeholder="请输入手机号"
											v-model="state.form.enterOrderValidate.mobile" />
						<el-select v-else-if="state.form.enterOrderValidate.sendType===1" v-model="state.form.enterOrderValidate.sendId" placeholder="请选择">
							<el-option v-for="user in state.userList" :label="user.nickName" :value="user.id" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item>
				<el-button type="primary" @click="submitForm(ruleFormRef)">
					确定创建
				</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>
<script setup lang="ts">
const fileUploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/api/file/upload?type=7`)
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
const size = ref<'default' | 'large' | 'small'>('default')
import { postRequest } from '~/composables/http'

const ruleFormRef = ref<FormInstance>()
const state = reactive(<any>{
	form: {
		enterOrderValidate: {
			paymentProof: '',
			payType: 0,
			sendType: 2,
		}
	},
	userList: []
})

watch(() => state.form.enterOrderValidate.payType, (newVal) => {
	if (newVal !== '0') {
		rules.paymentProof = [{ required: true, message: '请上传支付凭证', trigger: 'change' }]
	} else {
		delete rules.paymentProof
	}
})

// 动态添加/移除订单相关的验证规则
const toggleOrderValidation = () => {
	if (state.form.createOrder) {

		rules.amount = [{ validator: validateAmount, trigger: 'blur' }]
	} else {
		delete rules.orderName
		delete rules.amount
	}
}
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate((valid, fields) => {
		if (valid) {
			//如果需要订单
			if (state.form.createOrder){
				//订单名称
				if (!state.form.enterOrderValidate.orderName){
						ElMessage.error("订单名称不能为空！")
					return
				}
				//订单金额
				if (!state.form.enterOrderValidate.orderAmount){
					ElMessage.error("订单金额不能为空！")
					return
				}
				//支付类型
				if (state.form.enterOrderValidate.payType){
					//为直接付款
					if (state.form.enterOrderValidate.payType !== 0){
						if (!state.form.enterOrderValidate.paymentProof){
							ElMessage.error("直接付款必须上传凭证！")
							return
						}else {
							//删除凭证
							delete state.form.enterOrderValidate.paymentProof
						}
					}
				}
				//推送用户
				if (state.form.enterOrderValidate.sendType){
					if (state.form.enterOrderValidate.sendType === 2) {
						delete state.form.enterOrderValidate.mobile
						delete state.form.enterOrderValidate.sendId
					}
					//短信
					if (state.form.enterOrderValidate.sendType === 0) {
						if (!state.form.enterOrderValidate.mobile){
							ElMessage.error("推送方式为短信必须填写手机号！")
							return
						}else {
							if (!validateMobile(state.form.enterOrderValidate.mobile)){
								ElMessage.error("推送手机号格式不正确！")
								return
							}
						}
					}
					if (state.form.enterOrderValidate.sendType === 1) {
						if (!state.form.enterOrderValidate.sendId){
							ElMessage.error("推送方式为公众号必须选择用户！")
							return
						}
					}
				}
			}

			http.post('/api/admin/project/enter', state.form).then((response) => {
				toast.success("录入成功")
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}


function validateMobile(mobile) {
	// 正则表达式：匹配中国大陆手机号（以1开头，第二位为3-9，总共11位数字）
	const mobilePattern = /^1[3-9]\d{9}$/;

	// 如果匹配成功，返回 true，否则返回 false
	return mobilePattern.test(mobile);
}

const isValidAmount = (amount:any) => {
	const amountPattern = /^-?\d*(\.\d{0,2})?$/;
	return amountPattern.test(amount);
};

onMounted(() => {
	userInfo()
})

//代码更换上传钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
	//显示视频
	state.from.paymentProof = response.data.url
}

/**
 * 获取用户列表
 */
function userInfo() {
	let pageValidate = {
		pageNo: 1,
		pageSize: 999
	}
	postRequest('/api/admin/user/page', {
		pageValidate: { pageValidate: pageValidate },
		params: {}
	}).then((res: any) => {
		state.userList = res.data.lists
	})
}

const validateAmount = (rule, value, callback) => {
	const reg = /^[0-9]+(\.[0-9]{1,2})?$/
	if (!value) {
		return callback(new Error('请输入订单金额'))
	} else if (!reg.test(value)) {
		return callback(new Error('请输入正确的金额格式'))
	} else {
		callback()
	}
}
const rules = reactive<FormRules<any>>({
	code: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
	projectType: [{ required: true, message: '接单方式不能为空', trigger: 'blur' }],
	projectName: [{ required: true, message: '项目名称不能为空', trigger: 'change' }],
	projectCate: [{ required: true, message: '项目类别不能为空', trigger: 'change' }],
	amount: [{
			validator: (rule, value, callback) => {
				// 正则表达式：允许正负数、小数点最多两位
				const isValid = /^-?\d*(\.\d{0,2})?$/.test(value);
				if (!isValid) {
					callback(new Error('请输入有效的金额'));
				} else {
					callback(); // 验证通过
				}
			},
			trigger: 'change',
		},
	],
})

</script>
<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
